package com.htthorizon.util;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.util.StringUtil;
import com.htthorizon.model.domain.ModelMeta;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @author Brilliant
 */
@Component
@Slf4j
public class DynamicCreateTableUtil {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public String buildTableSql(String tableName,String tableNameZn ,List<ModelMeta> listModelMeta) {

        if (StringUtil.isEmpty(tableName) || listModelMeta == null) {

            throw new IllegalArgumentException("表参数不能为空");

        }

        StringBuilder sql = new StringBuilder("CREATE TABLE " + tableName + " (" + "id INT PRIMARY KEY auto_increment,");

        for (ModelMeta modelMeta : listModelMeta) {

            sql.append(modelMeta.getMetaFieldName())
                    .append(" ")
                    .append(this.ODPSType2MysqlType(modelMeta.getMetaFieldType()))
                    .append(" COMMENT '"+modelMeta.getMetaFieldRemark()+"'")
                    .append(",");

        }

        sql = new StringBuilder(sql.substring(0, sql.length() - 1));

        sql.append(") ENGINE=InnoDB auto_increment=1 DEFAULT CHARSET=utf8 COMMENT '"+tableNameZn+"'");

        log.info("动态生成 sql : {}", sql);

        return sql.toString();
    }

    private String ODPSType2MysqlType(String type) {
        if (type == null) {
            return "varchar(255)";
        }

        if (type.equals("integer")) {

            return "int";

        } else if (type.equals("string")) {

            return "varchar(255)";

        } else if (type.equals("DATE")) {

            return "datetime";

        } else if (type.equals("DATETIME")) {

            return "datetime";

        } else if (type.equals("DECIMAL")) {

            return "decimal";

        } else if (type.equals("TEXT")) {

            return "text";

        }

        return "varchar(255)";
    }

    public void executeSql(String sql) {

        if (StringUtil.isEmpty(sql)) {

            throw new IllegalArgumentException("sql 参数不能为空");

        }

        jdbcTemplate.execute(sql);

    }

    public String initData(String tableName, List<?> dataList) {

        for (int i = 0; i < dataList.size(); i++) {
            Map<String, Object> data = (Map<String, Object>) dataList.get(i);
            StringBuilder stringBuilder = generateInsertQuery(tableName, data);
            System.out.println("SQL:"+stringBuilder.toString());
            executeSql(stringBuilder.toString());
        }
        return null;
    }

    public void truncate(String tableName){
        log.info("初始化表数据");
        String sql="truncate table "+tableName;
        executeSql(sql);
    }


    private static StringBuilder generateInsertQuery(String tableName, Map<String, Object> data) {
        StringBuilder query = new StringBuilder();

        // INSERT INTO table_name (field1, field2, ...) VALUES (value1, value2, ...);
        query.append("INSERT INTO ");
        query.append(tableName).append(" (");

        for (Iterator<String> iterator = data.keySet().iterator(); iterator.hasNext(); ) {
            String key = iterator.next();

            if (!data.containsKey(key)) continue;

            query.append(key);

            if (iterator.hasNext()) {
                query.append(", ");
            } else {
                query.append(") VALUES (");

                for (Iterator<Object> valuesIterator = data.values().iterator(); valuesIterator.hasNext(); ) {
                    Object value = valuesIterator.next();

                    query.append("'").append(value).append("'");

                    if (valuesIterator.hasNext()) {
                        query.append(", ");
                    } else {
                        query.append(");");
                    }
                }
            }
        }

        return query;
    }


}
